package com.cskaoyan.market.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

@Component
@Aspect
public class SessionConversationAspect {
    @Autowired
    TransactionTemplate transactionTemplate;

    @Pointcut("@annotation(com.cskaoyan.market.anno.SessionConversation)")
    public void pt1(){}

    @Around("pt1()")
    public Object SessionConversationAdvice(ProceedingJoinPoint joinPoint){
        final Object[] proceed = {null};
        System.out.println("before anno");
        transactionTemplate.execute(new TransactionCallback<Object>(){
            @Override
            public Object doInTransaction(TransactionStatus status) {
                try {
                    //业务方法
                    System.out.println("transaction open "+status);
                    proceed[0] = joinPoint.proceed();
                } catch (Throwable e) {
//                    transactionTemplate.getTransactionManager().rollback(status);
                    System.out.println("transaction close "+status);
                    throw new RuntimeException(e);
                }
                System.out.println("transaction close "+status);
                return null;
            }
        });


        System.out.println("after anno");

        return proceed[0];
    }
}
